package com.yichou.test.filelock;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;

public class LockFileDemo {
	static final String FILE_PATH = "C:\\testlock.txt";

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		File file = new File(FILE_PATH);
		RandomAccessFile raf;
		
		try {
			raf = new RandomAccessFile(file, "rw");
			FileLock fl = raf.getChannel().tryLock();
			
			if(fl.isValid()){
				new Thread(new Runnable() { //写
					
					@Override
					public void run() {
						for (int i = 0; i < 10; i++) {
							FileWriter fw = null;
							
							try {
								fw = new FileWriter(FILE_PATH);
								fw.write("test write line " + i);
								fw.flush();
							} catch (IOException e1) {
								e1.printStackTrace();
							} finally {
								try {
									fw.close();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							
							try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}).start();
				
//				new Thread(new Runnable() {
//					@Override
//					public void run() {
//						for (int i = 0; i < 10; i++) {
//							FileReader fr = null;
//							
//							fr = new FileReader(FILE_PATH);
//							fr.read(cbuf);
//						}
//					}
//				}).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
